package com.glory.dmegcpda.view;


import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.glory.dmegcpda.MainActivity;
import com.glory.dmegcpda.R;
import com.glory.dmegcpda.adapter.ReleaseMsgAdapter;
import com.glory.dmegcpda.bean.PdfBean;
import com.glory.dmegcpda.utils.BitmapUtils;
import com.glory.dmegcpda.utils.DefaultItemTouchHelpCallback;
import com.glory.dmegcpda.utils.DefaultItemTouchHelper;
import com.glory.dmegcpda.utils.PdfItextUtil;
import com.glory.dmegcpda.utils.PdfUtils;
import com.glory.dmegcpda.viewmodel.PatrilModel;
import com.glory.mvvmnet.base.BaseActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.BaseFont;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;

import org.jetbrains.annotations.Nullable;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


/**
 * @author lenovo
 */
public class PatrolActivity extends BaseActivity<PatrilModel> implements View.OnClickListener {

    public static int PHOTO_IMAGE = 2;
    private RecyclerView pdf_recycler;
    private ArrayList<String> mList;
    private ArrayList<PdfBean> mPdfBeanList;
    private ReleaseMsgAdapter adapter;
    private Button tvTemporary, tvFinal, tvShowPDF;
    private PdfItextUtil pdfItextUtil;
    private ProgressDialog myDialog; // 保存进度框
    private static final int PDF_SAVE_START = 1;// 保存PDF文件的开始意图
    private static final int PDF_SAVE_RESULT = 2;// 保存PDF文件的结果开始意图
    private static final int PDF_SAVE_FIAL = 3;// 保存PDF文件的结果开始意图
    private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case PDF_SAVE_START:
                    if (!myDialog.isShowing()) {
                        myDialog.show();
                    }
                    break;

                case PDF_SAVE_RESULT:
                    if (myDialog.isShowing()) {
                        myDialog.dismiss();
                    }
                    mList.clear();
                    tvType.setText("");
                    etText.setText("");
                    adapter.notifyDataSetChanged();
                    Toast.makeText(PatrolActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    break;
                case PDF_SAVE_FIAL:
                    Toast.makeText(PatrolActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                    break;
            }
            return false;
        }
    });
    private FloatingActionButton fabutton;
    private FrameLayout frameLayout;
    private EditText etText;

    private List<String> mType;
    ImageView ivEqpTypeArrow;
    FrameLayout flEqpTypeList;
    TextView tvType;
    private FreeUI_GeneralPop mEqpTypePop;

    @Override
    public void initData() {
        mPdfBeanList = new ArrayList<>();
        mType = new ArrayList<>();
        mType.add("准备间");
        mType.add("划片室");
        mType.add("串焊");
        mType.add("上玻");
        mType.add("排版");
        mType.add("叠焊");
        mType.add("贴条码");
        mType.add("上EVA");
        mType.add("前EL");
        mType.add("层压");
        mType.add("翻转检验");
        mType.add("装框");
        mType.add("接线盒/灌胶");
        mType.add("接线盒检验");
        mType.add("固化");
        mType.add("IV");
        mType.add("绝缘/耐压测试");
        mType.add("后EL");
        mType.add("铭牌");
        mType.add("终检");
        mType.add("分档");
        mType.add("包装");
    }

    @Override
    public void initView(@Nullable Bundle bundle) {
        initProgress();
        mList = new ArrayList<>();
        pdf_recycler = findViewById(R.id.pdf_recycler);
//        frameLayout = findViewById(R.id.fl_menban);
        flEqpTypeList = findViewById(R.id.flEqpTypeList);
        ivEqpTypeArrow = findViewById(R.id.ivEqpTypeArrow);
        tvType = findViewById(R.id.tvType);
        etText = findViewById(R.id.etText);
        tvFinal = findViewById(R.id.tvFinal);
        tvShowPDF = findViewById(R.id.tvShowPDF);
        tvTemporary = findViewById(R.id.tvTemporary);
        flEqpTypeList.setOnClickListener(this::onClick);

        tvTemporary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mList.size() > 0) {
                    PdfBean pdfBean = new PdfBean();
                    pdfBean.setTitle(tvType.getText().toString());
                    pdfBean.setText(etText.getText().toString());
                    ArrayList<String> imageList = new ArrayList<>();
                    for (String s : mList) {
                        imageList.add(s);
                    }
                    pdfBean.setImageUrl(imageList);

                    mPdfBeanList.add(pdfBean);
                    mList.clear();
                    tvType.setText("");
                    etText.setText("");
                    adapter.notifyDataSetChanged();
                    Toast.makeText(PatrolActivity.this, "临时保存PDF", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(PatrolActivity.this, "没有选中图片", Toast.LENGTH_SHORT).show();
                }

            }
        });

        tvFinal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mList.size() > 0) {
                    for (int i = 0, len = mList.size(); i < len; i++) {
                        Log.e("TAG", "onActivityResult: 222" + mList.get(i));
                    }
                    toPDF();
                } else {
                    Toast.makeText(PatrolActivity.this, "没有选中图片", Toast.LENGTH_SHORT).show();
                }
                closeMemu();
            }
        });

        tvShowPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(PatrolActivity.this, LookPDFActivity.class));
                closeMemu();
            }
        });
        setRecyclerView();
    }

    @Override
    public int layoutId() {
        return R.layout.activity_patrol;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.flEqpTypeList:

                if (mEqpTypePop != null) {
                    if (mEqpTypePop.isShowing()) {
                        mEqpTypePop.dismiss();
                    }
                } else {
                    mEqpTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flEqpTypeList.getWidth(), mType, ivEqpTypeArrow, (codeS, i) -> {
                        tvType.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivEqpTypeArrow);
                mEqpTypePop.showAsDropDown(flEqpTypeList, 0, 0);
                break;
        }

    }

    /**
     * 初始化识别进度框
     */
    private void initProgress() {
        myDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        myDialog.setIndeterminateDrawable(getResources().getDrawable(
                R.drawable.progress_ocr));
        myDialog.setMessage("正在保存PDF文件...");
        myDialog.setCanceledOnTouchOutside(false);
        myDialog.setCancelable(false);

    }


    public void toPDF() {
        File file = new File(PdfUtils.ADDRESS);
        if (!file.exists()) {
            file.mkdirs();
        }
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        final String pdf_address = TestFilePathApkPrivate(this,
                Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator) + "/DMEGC_" + sdf.format(date) + ".pdf";

        Log.e("保存路径", pdf_address);

        handler.sendEmptyMessage(PDF_SAVE_START);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    pdfItextUtil = new PdfItextUtil(pdf_address);
                    //判断是否有图片没有土司提示选择图片
                    //如果有进行合成
                    if (mList.size() > 0) {
                        if (!mPdfBeanList.get(mPdfBeanList.size() == 0 ? 0 : mPdfBeanList.size() - 1).getTitle().equals(tvType.getText().toString())) {
                            PdfBean pdfBean = new PdfBean();
                            pdfBean.setTitle(tvType.getText().toString());
                            pdfBean.setText(etText.getText().toString());
                            ArrayList<String> imageList = new ArrayList<>();
                            for (String s : mList) {
                                imageList.add(s);
                            }
                            pdfBean.setImageUrl(imageList);
                            mPdfBeanList.add(pdfBean);
                        }
                        for (PdfBean pdfBean : mPdfBeanList) {
                            pdfItextUtil.addTitleToPdf(pdfBean.getTitle());
                            pdfItextUtil.addTextToPdf(pdfBean.getText());
                            for (int i = 0; i < pdfBean.getImageUrl().size(); i++) {
                                Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(pdfBean.getImageUrl().get(i)));
                                pdfItextUtil.addImageToPdfCenterH(pdfBean.getImageUrl().get(i), PageSize.A4.getWidth() - 20, PageSize.A4.getWidth() / bitmap.getWidth() * bitmap.getHeight());
                            }
                        }
                    } else {
                        Toast.makeText(PatrolActivity.this, "请选选择图片", Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(PDF_SAVE_FIAL);
                } finally {
                    if (pdfItextUtil != null) {
                        pdfItextUtil.close();
                    }
                    handler.sendEmptyMessage(PDF_SAVE_RESULT);
                }
            }
        }).start();
    }

    public Bitmap ScreenWindow() {
        getWindow().getDecorView().setDrawingCacheEnabled(true);
        Bitmap bmp = getWindow().getDecorView().getDrawingCache();
        return bmp;
    }

    private static final String SD_PATH = Environment.getExternalStorageDirectory().getPath() + "/fileimage/";
    private static final String IN_PATH = Environment.getExternalStorageDirectory().getPath() + "/fileimage/";

    public static String saveToBitmapfile(Bitmap bmp, String desFileName, Context context) {
        String savePath;
        File file;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            savePath = SD_PATH;
        } else {
            savePath = IN_PATH;
        }
        try {
            file = new File(savePath + generateFileName() + ".JPEG");
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return file.getAbsolutePath();
    }

    private static String generateFileName() {
        return UUID.randomUUID().toString();
    }


    public void closeMemu() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(fabutton, "rotation", -135, 20, 0);
        animator.setDuration(500);
        animator.start();
        AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0);
        alphaAnimation.setDuration(500);
        frameLayout.startAnimation(alphaAnimation);
        frameLayout.setVisibility(View.GONE);
    }

    private String TestFilePathApkPrivate(Context context, String FileDirName) {
        //不需要挂载测试，因为 app 都可以装 为什么 会没有数据
        String filedirpath = context.getExternalFilesDir(FileDirName).getPath();  //文件夹
        File fileDir = new File(filedirpath);                   //创建文件夹
        if (fileDir.exists()) {    //判断文件是否存在  很重要  别每次都会去覆盖数据
            fileDir.setWritable(true);
            Log.i("LOG_Info", "文件夹已经存在    TestFilePathInternalData（）");
        } else {
            try {
                fileDir.mkdir();
                Log.i("LOG_Info", "文件夹创建成功    TestFilePathExternalData（）");
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("LOG_Error", "文件夹创建错误   TestFilePathExternalData()" + e.getMessage());
            }
        }
        return filedirpath;
    }

    private void setRecyclerView() {

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        pdf_recycler.setLayoutManager(gridLayoutManager);
        adapter = new ReleaseMsgAdapter(this, getSupportFragmentManager(), mList);
        pdf_recycler.setAdapter(adapter);
        DefaultItemTouchHelper itemTouchHelper = new DefaultItemTouchHelper(new DefaultItemTouchHelpCallback.OnItemTouchCallbackListener() {

            @Override
            public boolean onMove(int srcPosition, int targetPosition) {
                // 更换数据源中的数据Item的位置
                Collections.swap(mList, srcPosition, targetPosition);
                // 更新UI中的Item的位置，主要是给用户看到交互效果
                adapter.notifyItemMoved(srcPosition, targetPosition);
                return true;
            }
        });
        itemTouchHelper.attachToRecyclerView(pdf_recycler);
        itemTouchHelper.setDragEnable(true);
        itemTouchHelper.setSwipeEnable(false);

    }


    /**
     * 设置PDF字体(较为耗时)
     */
    public Font setChineseFont() {
        BaseFont bf;
        Font fontChinese = null;
        try {
            // STSong-Light : Adobe的字体
            // UniGB-UCS2-H : pdf 字体
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            fontChinese = new Font(bf, 12, Font.NORMAL);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fontChinese;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            String path = BitmapUtils.getPath(this, BitmapUtils.imageUri);
//            mList.add(path);
            Bitmap bmpDefaultPic = BitmapFactory.decodeFile(path);
            Bitmap bitmap = rotateBitmapByDegree(bmpDefaultPic, getBitmapDegree(path));
            mList.add(saveToBitmapfile(bitmap, path, PatrolActivity.this));
            setRecyclerView();
        }
        if (requestCode == 2) {
//            List<AlbumPhoto> paths = RZAlbum.parseResult(data);
//            for (int i = 0, len = paths.size(); i < len; i++) {
//                mList.add(paths.get(i).getPhotoPath());
//            }
//            setRecyclerView();
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 读取图片的旋转的角度
     *
     * @param path 图片绝对路径
     * @return 图片的旋转角度
     */
    public static int getBitmapDegree(String path) {
        int degree = 0;//被旋转的角度
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    private static Uri createImageUri(Context context) {
        String name = "takePhoto" + System.currentTimeMillis();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.TITLE, name);
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, name + ".jpeg");
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        return uri;
    }
}
